package com.kuaifawu.lwnlawyerclient.Lib.LWNZxing.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.kuaifawu.lwnlawyerclient.Activity.LWNLognWebActivity;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.LWNZxing.camera.CameraManager;
import com.kuaifawu.lwnlawyerclient.Lib.LWNZxing.decoding.CaptureActivityHandler;
import com.kuaifawu.lwnlawyerclient.Lib.LWNZxing.decoding.InactivityTimer;
import com.kuaifawu.lwnlawyerclient.Lib.LWNZxing.view.ViewfinderView;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Vector;

/**
 * Initial the camera
 * @author Ryan.Tang
 */
public class CaptureActivity extends Activity implements Callback,View.OnClickListener {

	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;
	private Button cancelScanButton;
    private FrameLayout frame_logn;
    private ImageView logn;
    private View view=null;
    private ImageView cancel;
    private ImageView baground;
    private ImageView bagrounded;
    private ImageView cancel_web;
    private String saoCode="";
    private ImageButton saocode_back;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.capture_activity);
		//ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);
		CameraManager.init(getApplication());
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        saocode_back=(ImageButton)findViewById(R.id.saocode_back);
        saocode_back.setOnClickListener(this);
//		cancelScanButton = (Button) this.findViewById(R.id.btn_cancel_scan);
        view=getLayoutInflater().inflate(R.layout.logn_frament_view,null,false);
        frame_logn=(FrameLayout)findViewById(R.id.frame_logn);
        if(view!=null){
            logn=(ImageView)view.findViewById(R.id.logn);
			cancel=(ImageView)view.findViewById(R.id.cancel);
			baground=(ImageView)view.findViewById(R.id.baground);
			bagrounded=(ImageView)view.findViewById(R.id.bagrounded);
			cancel_web=(ImageView)view.findViewById(R.id.cancel_web);
			cancel.setOnClickListener(this);
			logn.setOnClickListener(this);
        }

		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
		
		//quit the scan view
//		cancelScanButton.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				CaptureActivity.this.finish();
//			}
//		});



	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}
	
	/**
	 * Handler scan result
	 * @param result
	 * @param barcode
	 */
    private String resultString="";
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		resultString = result.getText();
		//FIXME
		if (resultString.equals("")) {
			Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
		}else {
           // Toast.makeText(CaptureActivity.this, "成功", Toast.LENGTH_SHORT).show();
            try{
                JSONObject jsonObject = new JSONObject(resultString);
                saoCode = jsonObject.getString("code");
                saveCode("-1",saoCode);
            }catch (Exception e){
                e.printStackTrace();
                saoCode="";
                Intent intent=new Intent(CaptureActivity.this, LWNLognWebActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("code",saoCode);
                intent.putExtras(bundle);
                startActivity(intent);
            }
		}
	}
	
	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
//			handler = new CaptureActivityHandler(this, decodeFormats,
//					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};



    private void saveCode(String stu, final String code){
        final ProgressDialog proDialog = android.app.ProgressDialog.show(CaptureActivity.this, "", "加载中，请稍候...");
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        HttpUtils http=center.getUtils();
        String string_url = center.getInstance().getCode(stu, code, CaptureActivity.this);
        http.configCurrentHttpCacheExpiry(0);
        http.send(HttpRequest.HttpMethod.GET,string_url,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                proDialog.dismiss();
                try{

                    JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                    String string_code = jsonObject.getString("code");
                    String string_msg=jsonObject.getString("msg");
                    Intent intent=new Intent(CaptureActivity.this, LWNLognWebActivity.class);
                    Bundle bundle=new Bundle();
                    switch (string_code) {
                        case "10000":
                            //Toast.makeText(CaptureActivity.this, "访问成功", Toast.LENGTH_SHORT).show();
                            //JSONArray json_array = jsonObject.getJSONArray("data");
//                            Intent intent=new Intent(CaptureActivity.this, LWNLognWebActivity.class);
//                            Bundle bundle=new Bundle();
                            bundle.putString("code",saoCode);
                            intent.putExtras(bundle);
                            startActivity(intent);
                            //frame_logn.addView(view);
                            break;
//                        case "10001":
//
//                            break;
//                        case "10003":
//
//                            break;
                        default:
                            saoCode="";
//                            Intent intent=new Intent(CaptureActivity.this, LWNLognWebActivity.class);
//                            Bundle bundle=new Bundle();
                            bundle.putString("code",saoCode);
                            intent.putExtras(bundle);
                            startActivity(intent);
                            break;
                    }


                }catch (Exception e){
                    e.printStackTrace();
                    saoCode="";
                           Intent intent=new Intent(CaptureActivity.this, LWNLognWebActivity.class);
                            Bundle bundle=new Bundle();
                    bundle.putString("code",saoCode);
                    intent.putExtras(bundle);
                    startActivity(intent);

                }



            }

            @Override
            public void onFailure(HttpException e, String s) {
                proDialog.dismiss();
                saoCode="";
                Intent intent=new Intent(CaptureActivity.this, LWNLognWebActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("code",saoCode);
                intent.putExtras(bundle);
                startActivity(intent);

            }


        });





    }

    private void codeLogn(String code){
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        HttpUtils http=center.getUtils();
        String string_url = center.getInstance().getLogn(code, CaptureActivity.this);
        http.configCurrentHttpCacheExpiry(0);
        System.out.println("string_url=="+string_url);
        http.send(HttpRequest.HttpMethod.GET,string_url,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                try{
                    System.out.println("result=="+objectResponseInfo.result.toString());
                    JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                    String string_code = jsonObject.getString("code");
                    String string_msg=jsonObject.getString("msg");
                    switch (string_code) {
                        case "10000":
//                            Toast.makeText(CaptureActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
//                            JSONArray json_array = jsonObject.getJSONArray("data");


                            baground.setVisibility(View.GONE);
                            bagrounded.setVisibility(View.VISIBLE);
                            logn.setVisibility(View.INVISIBLE);
                            cancel.setVisibility(View.INVISIBLE);
                            cancel_web.setVisibility(View.VISIBLE);
                           // cancel_web.setBackgroundResource(R.drawable.quit_web);

                            break;
                        case "10001":

                            break;
                        case "10003":

                            break;
                    }


                }catch (Exception e){
                    e.printStackTrace();

                }



            }

            @Override
            public void onFailure(HttpException e, String s) {


            }


        });





    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
//            case R.id.logn:
//            try{
//                JSONObject jsonObject = new JSONObject(resultString);
//                String string_code = jsonObject.getString("code");
//                codeLogn(string_code);
//            }catch (Exception e){
//                e.printStackTrace();
//                   }
//                break;

//            case R.id.cancel:
//                hasSurface = true;
//                frame_logn.removeView(view);
//
//                break;
            case R.id.saocode_back:
                setResult(100);
                finish();
                break;
        }

    }
}